package com.cyh.pangu.offer;

import com.cyh.pangu.offer.common.ListNode;

public class Offer52 {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) {
            return null;
        }
        int headALength = 0;
        ListNode tempNodeA = headA;
        while (tempNodeA != null) {
            headALength++;
            tempNodeA = tempNodeA.next;
        }
        int headBLength = 0;
        ListNode tempNodeB = headB;
        while (tempNodeB != null) {
            headBLength++;
            tempNodeB = tempNodeB.next;
        }

        tempNodeA = headA;
        tempNodeB = headB;

        if (headALength > headBLength) {
            int flag = 0;
            while (flag < headALength - headBLength) {
                tempNodeA =  tempNodeA.next;
                flag++;
            }
        } else {
            int flag = 0;
            while (flag < headBLength - headALength) {
                tempNodeB =  tempNodeB.next;
                flag++;
            }
        }

        ListNode firstCommonHead = null;
        while (true) {
            if (tempNodeA == tempNodeB) {
                firstCommonHead = tempNodeA;
                break;
            } else {
                tempNodeA = tempNodeA.next;
                tempNodeB = tempNodeB.next;
            }
        }

        return firstCommonHead;
    }

    public static void main(String[] args) {

    }

}
